var region,url;
$(function () {
    region = $("#region");
    url = region.attr('data-url');
    region.find("select").select2();

    //选择省份
    region.find('#province').live('change', function(){
        if (url == undefined){
            region = $("#region");
            url = region.attr('data-url');
        }
        var province=$(this).val();
        city(province);
    });

    //选择城市
    region.find('#city').live('change', function(){
        var city = $(this).val();
        county(city);
    });
});

//省市联动
function city(province, id){
    if(province != ''){
        $.post(url,{parent_id:province},function(re){
            region.find("#city").find("option").remove();
            var city = "<option value=''>选择城市</option>";
            $.each( re, function(i,item){
                if (item['id'] == id){
                    city += "<option value='" + item['id'] + "' selected>" + item['name'] + "</option>";
                }else{
                    city += "<option value='" + item['id'] + "'>" + item['name'] + "</option>";
                }
            });
            region.find("#city").html(city);
            region.find("#city").select2();
        },'json');
        region.find("#county").html("<option>选择区县</option>");
        region.find("#county").select2();
    }
}

//市县联动
function county(city, id){
    if(city!=''){
        $.post(url,{parent_id:city},function(re){
            region.find("#county").find("option").remove();
            var county = "<option>选择区县</option>";
            $.each( re, function(i,item){
                if (item['id'] == id){
                    county += "<option value='" + item['id'] + "' selected>" + item['name'] + "</option>";
                }else{
                    county += "<option value='" + item['id'] + "'>" + item['name'] + "</option>";
                }
            });
            region.find("#county").html(county);
            region.find("#county").select2();
        },'json')
    }
}